package com.health.healthapplet.controller;


import com.health.healthapplet.entity.Response;
import com.health.healthapplet.entity.WxUser;
import com.health.healthapplet.service.WxService;
import com.health.healthapplet.utils.AuthUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


@RestController
@ResponseBody
public class WxUserController {
    @Autowired
    WxService wxService;
    @RequestMapping("/health-service/wxlogin")
    public void wx(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //第一步：引导用户进入授权页面同意授权，获取code
        StringBuilder builder = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize?appid=");
        builder.append(AuthUtil.APPID);
        builder.append("&redirect_uri=");
        builder.append(URLEncoder.encode(AuthUtil.backUrl));//开发文档要求转换
        builder.append("&response_type=code");
        builder.append("&scope=snsapi_userinfo");
        builder.append("&state=STATE#wechat_redirect");
        //授权页面地址
        //将StringBuilder转换成String
        String url=builder.toString();
        //重定向到授权页面
        response.sendRedirect(url);
    }

    /**
     * 微信登录回调
     */
    @RequestMapping(value="/callBack")
    public Response wxcallback(@RequestParam("code") String code, Model model)throws IOException {
        System.out.println("code:" + code);
        //获取code后，请求以下链接获取access_token
        StringBuilder builder = new StringBuilder("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
        builder.append(AuthUtil.APPID);
        builder.append("&secret=");
        builder.append(AuthUtil.APPSECRET);
        builder.append("&code=");
        builder.append(code);
        builder.append("&grant_type=authorization_code");

        //通过网络请求方法来请求上面这个接口
        //将StringBuilder转换成String
        String url=builder.toString();
        JSONObject jsonObject = AuthUtil.doGetJson(url);

        System.out.println("==========================jsonObject" + jsonObject);
        //从返回的JSON数据中取出access_token和openid，拉取用户信息时用
        String token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        // 第三步：刷新access_token（如果需要）
        // 第一种写法
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+token
                + "&openid="+openid
                + "&lang=zh_CN";
        //第二种写法
//        StringBuilder builder1 = new StringBuilder("https://api.weixin.qq.com/sns/userinfo?access_token=");
//        builder1.append(token);
//        builder1.append("&openid=");
//        builder1.append(openid);
//        builder1.append("&lang=zh_CN");
//        //通过网络请求方法来请求上面这个接口
//        //将StringBuilder转换成String
//        String infoUrl=builder1.toString();
        // 第四步：拉取用户信息(需scope为 snsapi_userinfo)
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);

        System.out.println("userInfo=======" + userInfo);

        //第1种情况：使用微信用户信息直接登录，无需注册和绑定
//        model.addAttribute("info",userInfo);
//        return "wx/wxtest1";
//

        //第2种情况：查看数据库是否存在相对应用户
        try {
            WxUser wxuser = new WxUser();
            wxuser = wxService.findnameByopenId(openid);
            System.out.println("wxuser=======" + wxuser);
            if (wxuser != null) {
                //已绑定
                model.addAttribute("info",userInfo);
                model.addAttribute("name", wxuser.getName());
                Response response = new Response("已授权成功",1,true);
                return response;

            } else {
                //未绑定
                model.addAttribute("openid", openid);
                model.addAttribute("info",userInfo);
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("openid", openid);
                dataMap.put("info", userInfo);
                Response response = new Response();
                response.setResponse(true,"授权成功",200,dataMap);
                return response;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Response response = new Response("授权失败",1,true);
        return response;
    }

    /**
     * 微信登录成功后将用户信息插入数据库
     */
    @RequestMapping(value="/health-service/addwxuser")
    public Response addWXuser(@RequestParam("openid") String openid,@RequestParam("name") String name,@RequestParam("sex") String sex,@RequestParam("city") String city,@RequestParam("urlimg") String urlimg){

        int count = wxService.addWxuser(openid,name,sex,city,urlimg);
        if(count>0){
            Response response = new Response("添加成功",1,true);
            return response;
        }
        Response response = new Response("添加失败",-1,false);
        return response;
//        return "wx/success";//跳转绑定成功页面

    }
}